import { useCallback, useMemo, useRef, useState } from 'react';
import { Button, Modal, Tabs } from 'antd';
import { useCurrentNode } from '@inbiz/react';
import { TreeNode } from '@inbiz/core';
import Operation, { IOperationData, IOperationRef } from './operation';
import Subwindow, { ISubwindowData, ISubwindowRef } from './subwindow';
import { useUpdateEffect } from 'ahooks';
import { uuid } from '@inbiz/utils';
export type IConfig = {
  operation?: IOperationData;
  subwindow?: ISubwindowData;
};

function Config<T extends IConfig>({
  value,
  onChange,
}: {
  value: T;
  onChange: (value: T) => void;
}) {
  const currentNode = useCurrentNode() as TreeNode;

  // 显示隐藏
  const [visible, $visible] = useState(false);
  const [activeKey, $activeKey] = useState('operation');

  // 判断按钮组是否在 表格控件中
  const isInTable = useMemo(() => {
    // 弹框打开时才重新计算
    if (visible) {
      let initStatus = false,
        node = currentNode.parent;
      while (!initStatus && node) {
        if (node.props?.['x-component'] === 'Table') {
          initStatus = true;
        } else {
          node = node.parent;
        }
      }
      return initStatus;
    } else {
      return false;
    }
  }, [visible]);
  // 操作类型的集合

  // 更新展示数据
  const [curValue, $curValue] = useState<IConfig>(() => value || {});
  useUpdateEffect(() => {
    if (visible) {
      $curValue(value);
    }
  }, [value, visible]);

  const parentOptions = useMemo(() => {
    return (
      curValue.operation?.list
        ?.filter((item) => item.type === 'custom')
        .map((item) => ({ value: item.id, label: item.name })) || []
    );
  }, [curValue.operation?.list]);

  const operationRef = useRef<IOperationRef>(null);
  const subwindowRef = useRef<ISubwindowRef>(null);

  const handleChange = useCallback((key:any) => {
    if (key === 'subwindow') {
      operationRef.current?.getValue().then((res) => {
        $curValue((value:any) => {
          let list = updateSubwindowList(res?.list, value.subwindow?.list);
          return { subwindow: { ...value.subwindow, list }, operation: res };
        });
        $activeKey(key);
      });
    } else {
      subwindowRef.current?.getValue().then((res) => {
        $curValue((value) => ({ ...value, subwindow: res }));
        $activeKey(key);
      });
    }
  }, []);

  const handleOk = useCallback(async () => {
    const operation = await operationRef.current?.getValue(true).catch((e) => {
      $activeKey('operation');
      return Promise.reject(e);
    });
    const subwindow = subwindowRef.current
      ? await subwindowRef.current?.getValue().catch((e) => {
          $activeKey('subwindow');
          return Promise.reject(e);
        })
      : {};

    subwindow.list = updateSubwindowList(operation?.list, subwindow.list);
    onChange({ operation, subwindow } as T);
    $visible(false);
  }, [isInTable, onChange]);

  return (
    <>
      <Button type="primary" onClick={() => $visible(true)}>
        配置
      </Button>
      <Modal
        title="配置"
        width={1142}
        visible={visible}
        onCancel={() => $visible(false)}
        onOk={handleOk}
        destroyOnClose
      >
        <Tabs activeKey={activeKey} onChange={handleChange}>
          <Tabs.TabPane tab="操作" key={'operation'} forceRender>
            <Operation value={curValue.operation} isInTable={isInTable} ref={operationRef} />
          </Tabs.TabPane>
          <Tabs.TabPane tab="子窗体" key={'subwindow'} forceRender>
            <Subwindow
              parentOptions={parentOptions}
              value={curValue.subwindow}
              ref={subwindowRef}
            />
          </Tabs.TabPane>
        </Tabs>
      </Modal>
    </>
  );
}

export default Config;

// 根据operation.list 更新subwindow.list
function updateSubwindowList(
  operationList?: IOperationData['list'],
  subwindowList?: ISubwindowData['list'],
) {
  if (!operationList?.length) {
    return [];
  }
  const operationIDs = operationList.map((item) => item.id);
  // 删除 不存在的父级项
  const sList = subwindowList?.filter((item) => operationIDs.includes(item.parent)) || [];
  if (!sList?.length) {
    // 为空时, 父级操作为自定义并绑定页面时， 自动生成生成两个子操作
    return operationList
      .filter((item) => item.type === 'custom' && item.page)
      ?.map((item) => {
        return [
          {
            type: 'save',
            parent: item.id,
            name: 'EformButtonGroup.button.save',
            id: uuid(10, 5),
          },
          {
            type: 'cancel',
            parent: item.id,
            name: 'EformButtonGroup.button.cancel',
            id: uuid(10, 5),
          },
        ];
      })
      .flat() as typeof subwindowList;
  } else {
    return sList;
  }
}
